<template>
  <!-- style={{width: showWidth, ...style}} -->
  <div className="jh-temperature-chart">
    <div class="test">1111111111</div>
    <TemperatureBody v-if="newConfig" :config="newConfig" :data="data" />
    <TemperatureFooter :configXml="config" :footerConfig="footerConfig" />
    <!-- <TemperatureFooter v-if="newConfig" :config="newConfig" />  -->
    <!-- <TemperatureBody :config="newConfig" :data="data" />
    <TemperatureFooter :configXml="config" /> -->
  </div>
</template>

<script setup lang="ts">
import {
  reactive,
  ref,
  onBeforeUnmount,
  onMounted,
  computed,
  watch,
  getCurrentInstance,
} from "vue";

// import TemperatureDesign from "./temperatureDesign/index.vue";

// import TemperatureData from "./temperatureData/index.vue";

import DesignUtils from "./DesignUtils";
import Design2Utils from "./Design2Utils";

import ParseXML from "./parseXML";
import parseStringToXml from "./parseStringToXml";

import moment from "moment";

// import vitalSignText from "./vitalsign.ts";

import Custom_Variable from "./CUSTOM";

import { Base64 } from "js-base64";

import TemperatureBody from "./TemperatureBody.vue";
import TemperatureFooter from "./temperatureFooter/index.vue";

let parseXML = new ParseXML();

let props = defineProps({
  parsedSetting: Object,
  config: Object,
  data: Array,
  size: Number,
  scale: Number,
  beginDate: String,
  patient: Object,
  footerConfig: Object,
  authority: Object,
  unit: String,
  style: Object,
  noHandle: Object,
});

let showWidth: number = ref(0);
let showHeight: number = ref(0);
let newConfig = ref();

/**
 * @method 解析出体温单的配置数据
 */
let parseTempConfig = (configJson: any) => {

console.log("444configJson",configJson);


  let { config: configXml, data: dataJson, ...other } = configJson;

  const designUtils = new DesignUtils({ configJson, ...other });

  // 体温单线条/字体/图标/绘制规则等配置信息
  const config = {
    vitalLineOutToConfig: designUtils.getVitalLineOutToConfig(),
    vitalLineOverlapToConfig: designUtils.getVitalLineOverlapToConfig(),
    vitalTextOutToConfig: designUtils.getVitalTextOutToConfig(),
    vitalLineBlockToConfig: designUtils.getVitalLineBlockToConfig(),
    vitalRegionFillToConfig: designUtils.getVitalRegionFillToConfig(),
    vitalShowToConfig: designUtils.getVitalShowToConfig(),
    fontIdToStyle: designUtils.getFontIdToStyle(),
    linePenIdToStyle: designUtils.getLineIdToStyle(),
    symbolIdToStyle: designUtils.getSymbolIdToStyle(),
  };

  // 体温单底板设置数据
  const designData = {
    vitalLines: designUtils.getVitalLines(),
    vitalTexts: designUtils.getVitalTexts(),
  };

  const showSize = designUtils.getShowSize();
  const keyToNumber = designUtils.getKeyToNumber();
  const showRect = designUtils.getRectSize();

  let items = props.data || [];

  items = resetItems(items, config);

  // 体温单显示数据
  const showData = {
    items: items,
    vitalTextOuts: designUtils.getVitalTextOuts(),
  };

  return { config, designData, showData, showSize, showRect, keyToNumber };
};

/**
 * @method 将数据解析成所需格式
 * @param items
 * @param config
 */
const resetItems = (items: any, config: any) => {
  // const {splitNumber, beginDate} = temperatureConfigData;

  let splitNumber = 4;
  let beginDate = "2025-07-31 00:00:00";

  let newItems = [];
  // 时间拆分配置 splitType：1时间点不拆分小格 2全局均分，精确到分显示 3时间点拆分成小格
  let vitalShowToConfig = config.vitalShowToConfig || {};
  let splitType = (vitalShowToConfig["时间"] || {}).splitType;
  let disScale;
  let splitBeginNumber = 0;

  for (let i = 0; i < items.length; i++) {
    let {
      name,
      index,
      innerIndex,
      value,
      otherValue,
      customName,
      date,
      flag,
      subArray,
      ...other
    } = items[i];
    let disIndex = 0;
    if (splitType && innerIndex < 5 && splitType != 2) {
      if (splitType == 3) {
        splitBeginNumber = 2;
      }
      disIndex = (innerIndex - splitBeginNumber) / splitNumber;
    }
    if (splitType == 2) {
      // 总共显示7天， 计算当前时间到开始时间
      let totalTimes = 7 * 24 * 60 * 60 * 1000;
      let disTimes = moment(date) - moment(beginDate);
      disScale = disTimes / totalTimes;
    }
    let threeValue = null;
    let beforeValue = null;
    let afterValue = null;
    let specialShow = false;
    // 大便次数特殊处理， 如果出现-4/N则去掉前面的-号
    // 显示格式：flag:2 N-n/E； flag:1 Nn/E
    if (name === "大便次数") {
      let config = parseShitValue(value, flag);
      beforeValue = config.beforeValue;
      afterValue = config.afterValue;
      specialShow = config.specialShow;
      threeValue = Custom_Variable.isEnema ? config.threeValue : null;

      if (subArray) {
        subArray = subArray.map((item: any) => {
          return {
            ...item,
            ...parseShitValue(item.value, item.flag),
            flag: null,
          };
        });
      }
      flag = null;
    }

    // 呼吸特殊处理， flag为1时，添加呼吸机，显示值R
    let showName = name.replace("UP", "").replace("DOWN", "");
    let cacheName = showName;
    /**
     * 下列部分需要修改
     */
    // if(showName==='呼吸' && flag==1){
    //   newItems.push({
    //     '_attr': {
    //       vitalsigns: '呼吸机',
    //       vitalsignsvalues: 'R',
    //       cellindex: index + disIndex,
    //       date: date,
    //       disScale: disScale, //显示位置在整个体温单中所占比列
    //       subItem: subArray?subArray.map(item=>{
    //         return {
    //           ...item,
    //           value: item.flag==1?'R': item.value,
    //         }
    //       }): subArray,
    //       flag: null,
    //     }
    //   });
    //   showName = `${showName}DOWN`;
    // }

    newItems.push({
      _attr: {
        vitalsigns: flag == 1 ? showName : name,
        vitalsignsvalues: value,
        vitalsignsoriginalvalues: otherValue,
        cellindex: index + disIndex,
        mainName: customName,
        date: date,
        flag: customName ? 0 : cacheName == "呼吸" ? "" : flag, // 该flag定义颜色
        isCus: customName ? true : false, // 如果是自定义项才取该标识，表示是否是录入的自定项
        subItem: subArray,
        ...other,
        disScale: disScale, //显示位置在整个体温单中所占比列
        beforeValue: beforeValue, // 大便灌肠的第一个输入框
        afterValue: afterValue, // 大便灌肠的第二个输入框
        specialShow: specialShow,
        threeValue: threeValue, // 大便灌肠的第三个输入框
      },
    });
  }

  // 配置了脉搏短绌则解析数据
  if (
    config.vitalRegionFillToConfig &&
    config.vitalRegionFillToConfig["脉搏短绌"]
  ) {
    let mbdcPoints = getMbdcPoints(newItems);
    newItems = newItems.concat(mbdcPoints);
  }

  return newItems;
};

let getMbdcPoints = (items: any) => {
  // 解析生成脉搏短促数据， 同一时间内，脉搏小于心率
  let mbdcPoints = [];
  let mbdc = [];
  let xlPoints = items.filter((v) => v["_attr"].vitalsigns === "心率");
  let mbPoints = items.filter((v) => v["_attr"].vitalsigns === "脉搏");
  let indexSub = 0;

  let indexs = Array.from(
    new Set(
      xlPoints
        .map((v) => v["_attr"].cellindex)
        .concat(mbPoints.map((v) => v["_attr"].cellindex))
    )
  );
  indexs.sort((a, b) => a - b);

  for (let i = 0; i < indexs.length; i++) {
    let index = indexs[i];
    let xlPoint = xlPoints.find((v) => v["_attr"].cellindex === index);
    // index, innerIndex
    let mbPoint = mbPoints.find((v) => v["_attr"].cellindex === index);

    if (
      xlPoint &&
      mbPoint &&
      xlPoint["_attr"].vitalsignsvalues &&
      mbPoint["_attr"].vitalsignsvalues &&
      mbPoint["_attr"].vitalsignsvalues < xlPoint["_attr"].vitalsignsvalues
    ) {
      if (!mbdc[indexSub]) {
        mbdc[indexSub] = [];
      }
      mbdc[indexSub].push(mbPoint);
      mbdc[indexSub].unshift(xlPoint);
    } else {
      indexSub++;
      continue;
    }
  }

  mbdc = mbdc.filter((v) => !!v);

  for (let i = 0; i < mbdc.length; i++) {
    mbdc[i] = mbdc[i].map((v) => {
      return {
        _attr: {
          ...v["_attr"],
          vitalsigns: "脉搏短绌",
          groupName: `脉搏短绌${i}`,
        },
      };
    });
    mbdcPoints = mbdcPoints.concat(mbdc[i]);
  }

  return mbdcPoints;
};

/**
 * 解析大便值
 */
let parseShitValue = (value: any, flag: any) => {
  let beforeValue, afterValue, specialShow, threeValue;
  if (`${value}`.indexOf("/") > -1) {
    let valueArray = (value.split("/")[0] || "").split("-");
    if (Custom_Variable.isEnema)
      threeValue = (value.split("/")[1] || "").replace("E", "");
    // 解析一下数据
    if (`${value}`.substring(0, 1) === "-") {
      value = `${value}`.substring(1, `${value}`.length);
    }
    if (flag == 2) {
      if (valueArray.length === 2) {
        beforeValue = valueArray[0];
        afterValue = valueArray[1];
        specialShow = true;
      } else if (valueArray.length === 1) {
        afterValue = valueArray[0];
        specialShow = true;
      }
    }
  }
  return {
    threeValue: threeValue || "",
    beforeValue,
    afterValue,
    specialShow,
  };
};

onMounted(() => {
  // const {headerRender, footerRender, unit, scale, data: dataJson, config: configXml, style, ...other} = this.props;

  //重新组装parsedSetting配置文件
  let configJsonObj = {
    vitalsign: null,
  };

  if (props.parsedSetting && props.parsedSetting.children) {
    configJsonObj.vitalsign = [];

    let item = {};

    props.parsedSetting.children.forEach((element: any) => {
      if (!item[element.tagName]) {
        item[element.tagName] = [{}];
      } 
      if (element.children) {
          element.children.forEach((child: any) => {
            if (!item[element.tagName][0][child.tagName]) {
              item[element.tagName][0][child.tagName] = [];
            }
            item[element.tagName][0][child.tagName].push({
              _attr: child.attributes,
              _text: [null],
            });
          });
        }else{
          item[element.tagName][0]={
            _attr: element.attributes,
              _text: [null],
          };
        }
      // configJsonObj.vitalsign[0][element.tagName] = element.children
    });

    configJsonObj.vitalsign.push(item);
  }


  let configJson = parseXML.xmlToJson(props.config);
  // configJson = configJsonObj
  console.log("11111configJson2", configJsonObj);
  console.log("11111configJson", configJson);

  // if (!configJson["vitalsign"]) {
  //   console.log("11111", "配置错误");
  //   return;
  // } else {
  //   console.log("11111", "配置正确");
  // }

  if (props.parsedSetting.tagName != "vitalsign") {
    console.log("11111", "配置错误");
    return;
  } else {
    console.log("11111", "配置正确");
  }

  let { config, designData, showData, showSize, keyToNumber, showRect } =
    parseTempConfig(configJson);

  let { showWidth, showHeight } = showSize || {};
  // unit={unit}
  //         scale={scale}
  //         showSize={showSize}
  //         showRect={showRect}
  //         keyToNumber={keyToNumber}
  //         {...other}
  //         temperatureChartInstance={this.printDom}

  let newConfigObj = {
    config: config,
    designData: designData,
    showData: showData,
    unit: props.unit,
    scale: props.scale,
    noHandle: props.noHandle,
    showSize: showSize,
    showRect: showRect,
    keyToNumber: keyToNumber,
  };

  newConfig.value = newConfigObj;

  // let { config, designData, showData, showSize, showRect } = props.config;

  // showWidth.value = showSize.showWidth;
  // showHeight.value = showSize.showHeight;

  // console.log("config", props.config, props.data, showSize);
});
</script>

<style scoped>

  .test{
    font-size: 16px;
  }


</style>
